﻿using Common.Helper;
using IRepository;
using IService.Entity;
using Microsoft.Extensions.Logging;
using Model;
using Newtonsoft.Json;
using SqlSugar.Extensions;
using StackExchange.Profiling;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Service.Entity
{
    public class BUserService: IBUserService
    {
        readonly ILogger<BUserService> logger;
        readonly IBaseRepository baseRepository;
        public BUserService(ILogger<BUserService> _logger, IBaseRepository _baseRepository)
        {
            logger = _logger;
            baseRepository = _baseRepository;
        }

        #region Get


        /// <summary>
        /// 查询所有用户（分页）
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> GetAllToPage(int offset, int limit)
        {
            try
            {
                PageInfoModel<BUser> pageList = await baseRepository.QueryPage<BUser>(offset, limit, "ID");

                PageInfoModel<object> list = new PageInfoModel<object>();
                list.DataCount = pageList.DataCount;
                list.PageSize = pageList.PageSize;
                list.PageCount = pageList.PageCount;
                list.Page = pageList.Page;
                list.Data = new List<object>();
                foreach (var item in pageList.Data)
                {
                    BRole role = baseRepository.Query<BRole>(n => n.ID == item.RoleId).Result.FirstOrDefault();
                    list.Data.Add(new
                    {
                        id=item.ID,
                        roleID=item.RoleId,
                        roleName = role.RoleName,
                        userName=item.UserName,
                        password=item.Password,
                        nickName=item.NickName,
                        state=item.State,
                        createdAt = item.CreatedAt,
                        updatedAt = item.UpdatedAt
                    });
                };

                string result = JsonConvert.SerializeObject(list);
                return new MessageModel<string>()
                {
                    Code = 20000,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 获取用户
        /// </summary>
        /// <param name="jsUser">用户对象</param>
        /// <returns></returns>
        public async Task<BUser> GetUser(BUser jsUser)
        {
            var user = await baseRepository.Query<BUser>((Expression<Func<BUser, bool>>)(n => n.UserName == jsUser.UserName && n.Password == jsUser.Password));

            return user.FirstOrDefault();
        }

        /// <summary>
        /// 查询所有用户
        /// </summary>
        /// <param name="jsUser"></param>
        /// <returns></returns>
        public async Task<MessageModel<List<BUser>>> GetAll()
        {
            try
            {
                List<BUser> result = await baseRepository.Query<BUser>();
                //string FunName = MethodBase.GetCurrentMethod().DeclaringType.Name;//获取当前方法名
                //FunName = FunName.Substring(FunName.IndexOf('<')+1,FunName.LastIndexOf('>')-1);
                //LogLock.OutLogFile("UserService_GetAll", "", JsonConvert.SerializeObject(result), true);//存入日志
                return new MessageModel<List<BUser>>()
                {
                    Code = 200,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<List<BUser>>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 根据条件表达式查询数据列表
        /// </summary>
        /// <param name="whereExpression">条件表达式</param>
        /// <returns>数据列表</returns>
        public async Task<MessageModel<List<BUser>>> GetByExpression<BUser>(Expression<Func<BUser, bool>> whereExpression)
        {
            try
            {
                List<BUser> result = await baseRepository.Query(whereExpression);
                //LogLock.OutLogFile("GetByExpression", JsonConvert.SerializeObject(whereExpression), JsonConvert.SerializeObject(result), true);//存入日志
                return new MessageModel<List<BUser>>()
                {
                    Code = 200,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<List<BUser>>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 查询角色按用户名密码
        /// </summary>
        /// <param name="jsUser"></param>
        /// <returns></returns>
        public async Task<MessageModel<BUser>> GetByNameAndPwd(string Name, string Pwd)
        {
            try
            {
                BUser user;
                //通过账户获取用户信息，code 应是唯一性，新增用户需要考虑这点
                using (MiniProfiler.Current.Step("通过账户获取用户信息："))
                {
                    user = (await baseRepository.Query<BUser>((Expression<Func<BUser, bool>>)(t => t.UserName == Name))).FirstOrDefault();
                }

                if (user == null)
                {
                    return new MessageModel<BUser>()
                    {
                        Code=200,
                        Success = false,
                        Message = "账号不存在!",
                    };
                }
                else
                {
                    //获取用户密码 比对输入的密码
                    if (!MD5Helper.MD5Decrypt(Pwd, user.Password))
                    {
                        return new MessageModel<BUser>()
                        {
                            Code = 200,
                            Success = false,
                            Message = "密码错误!",
                        };
                    }
                    //LogLock.OutLogFile("GetById", JsonConvert.SerializeObject(id), JsonConvert.SerializeObject(result), true);//存入日志
                    return new MessageModel<BUser>()
                    {
                        Code = 200,
                        Data = user,
                        Message = "查询成功!",
                        Success = true
                    };
                }
                
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<BUser>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }


        /// <summary>
        /// 查询用户按ID
        /// </summary>
        /// <param name="jsUser"></param>
        /// <returns></returns>
        public async Task<MessageModel<BUser>> GetById(int id)
        {
            try
            {
                BUser result = await baseRepository.Query<BUser>(id);
                //LogLock.OutLogFile("GetById", JsonConvert.SerializeObject(id), JsonConvert.SerializeObject(result), true);//存入日志
                return new MessageModel<BUser>()
                {
                    Code = 200,
                    Data = result,
                    Message = "查询成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<BUser>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }
        #endregion

        #region Post
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="jsUser"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> Post(BUser bUser)
        {
            try
            {
                bUser.CreatedAt = DateTime.Now;
                //密码加密
                bUser.Password = MD5Helper.MD5SaltEncryp(bUser.Password);
                //获取用户ID
                bUser.ID = await baseRepository.Add(bUser);
                //LogLock.OutLogFile("Post", JsonConvert.SerializeObject(jsUser), JsonConvert.SerializeObject(jsUser), true);//存入日志
                return new MessageModel<string>()
                {
                    Code = 200,
                    Data = bUser.ID.ObjToString(),
                    Message = "添加成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        #endregion

        #region Put
        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="jsUser"></param>
        /// <returns></returns>
        public async Task<MessageModel<string>> Put(BUser bUser)
        {
            try
            {
                bUser.Password = MD5Helper.MD5SaltEncryp(bUser.Password);
                bool flag = await baseRepository.Update(bUser);
                if (flag)
                {
                    return new MessageModel<string>()
                    {
                        Code = 200,
                        Data = bUser.ID.ObjToString(),
                        Message = "修改成功",
                        Success = true
                    };
                }
                return new MessageModel<string>()
                {
                    Data = null,
                    Message = "修改失败",
                    Success = false
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="id">用户ID</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public async Task<MessageModel<string>> Reset(int id, string password)
        {
            try
            {
                BUser user = baseRepository.Query<BUser>(n=>n.ID==id).Result.FirstOrDefault();
                user.Password = MD5Helper.MD5SaltEncryp(password);
                bool flag = await baseRepository.Update(user);
                if (flag)
                {
                    return new MessageModel<string>()
                    {
                        Code = 200,
                        Data = user.ID.ObjToString(),
                        Message = "重置成功",
                        Success = true
                    };
                }
                return new MessageModel<string>()
                {
                    Data = null,
                    Message = "重置失败",
                    Success = false
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<string>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        #endregion

        #region Delete
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="jsUser"></param>
        /// <returns></returns>
        public async Task<MessageModel<bool>> DelById(int id)
        {
            try
            {
                bool flag = await baseRepository.DeleteById<BUser>(id);
                //LogLock.OutLogFile("DelById", JsonConvert.SerializeObject(id), JsonConvert.SerializeObject(flag), true);//存入日志
                return new MessageModel<bool>()
                {
                    Code = 200,
                    Data = flag,
                    Message = "删除成功",
                    Success = true
                };
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.Message);
                return new MessageModel<bool>()
                {
                    Code = 500,
                    Message = "服务异常:" + ex.Message,
                    Success = false
                };
            }
        }

        #endregion

    }
}
